#if !SERVER
using ActorSystem;
using Example2;
using Net.Client;
using Net.Share;
using UnityEngine;

namespace Example2
{
    public partial class Bullet : ActorBase, IActorOnCollisionEnter
    {
        internal Player target;
        public GameObject explosionPrefab;

        public override void OnOperation(in Operation opt)
        {
            switch (opt.cmd)
            {
                case Command.EnterArea:
                    EnterArea(opt);
                    break;
            }
        }

        protected virtual void EnterArea(in Operation opt)
        {
            var viewPrefab = GetViewPrefab();
            View = Object.Instantiate(viewPrefab);
            View.Actor = this;
            View.transform.SetPositionAndRotation(opt.position, opt.rotation);
            View.gameObject.SetActive(true);
        }

        private ActorView GetViewPrefab()
        {
            return Object.FindAnyObjectByType<SceneManager>().actorViews[2];
        }

        public void OnCollisionEnter(Collision collision)
        {
            var view = collision.collider.GetComponent<ActorView>();
            if (view.Actor == target)
                return;
            var contact = collision.contacts[0];
            var rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
            var pos = contact.point;
            var explosion = Object.Instantiate(explosionPrefab, pos, rot);
            Object.Destroy(explosion, 1f);
            target.AddOperation(new Operation(Command.Damage, Identity, view.Actor.Identity) { uid = target.Identity });
            Object.Destroy(View.gameObject);
        }
    }
}
#endif
